'use strict'

class content {

  constructor() {
    //param默认就是/:id，若要改变路由，则可以设置此属性，比如设置为/:name
    //this.param = '/:id'
  }

  //只对当前这个文件里的post和delete起作用
  __mid() {
    return [
      {
        name: 'token-verify',
        path: ['post', 'delete']
      }
    ]
  }

  //以下方法，若不需要，要去掉，避免无意义的路由。

  //获取资源具体内容
  //对应路由GET /content/:id
  async get(c) {
    let id = c.param.id

    let sqltext = 'SELECT id,detail,title,update_time '
      + ' FROM content WHERE id=$1';

    //依赖录入，每一个回调函数的c.service都会指向app的service，实现轻量级引用
    let r = await c.service.psql.query(sqltext, [id])

    if (r.rowCount === 0) {
      return c.status(404).send('not found');
    }

    c.send(r.rows[0])
  }

  //创建资源
  //对应路由POST /content
  async post(c) {
    try {
      //c.body是我交的请求体数据
      let data = JSON.parse(c.body);
      let sqltext = 'INSERT INTO content'
        + '(id,detail,title,add_time,update_time)'
        + 'VALUES($1,$2,$3,$4,$5)'

      //随机数转成16进制字符串并去掉前两位，字符串作为ID
      let id = Math.random().toString(16).substring(2)
      //c.helper.makeId(16)随机生成16位的id
      let tm = Date.now()

      let r = await c.service.psql.query(sqltext, [
        id, data.detail, data.title, tm, tm
      ])

      if (r.rowCount === 0) {
        return c.status(500).send('failed')
      }

      c.send(id)
    } catch (err) {
      console.log(err)
      s.status(400).send('bad data')
    }
  }

  //更新资源
  //对应路由PUT /content/:id
  async put(c) {

  }

  //获取列表
  //对应路由GET /content
  async list(c) {
    let sqltext = 'SELECT id,title,update_time FROM content';
    let r = await c.service.psql.query(sqltext);

    c.send(r.rows);
  }

  //删除资源
  //对应路由DLETE /content/:id
  async delete(c) {
    let r = await c.service.psql.query(`DELETE FROM content WHERE id=$1`, [c.param.id])

    c.send({
      count: r.rowCount
    })
  }

}

module.exports = content
